package com.example.dadabase

import android.content.Context
import androidx.room.AutoMigration
import androidx.room.Room
import androidx.room.migration.AutoMigrationSpec
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.example.dadabase.AppDataBase
import java.sql.SQLException

/**
 * 优化：冷启动优化（第一次启动）
 *      基本优化思路：1.把好事操作放到子线程
 */
object RoomDBUtils {
    private const val parkDataBaseName="smart_park.db"
    private lateinit var roomDb: AppDataBase
    private val MIGRATION_2_3=object :Migration(2,3){
        override fun migrate(database: SupportSQLiteDatabase) {
           try {
               //SQL语句来升级数据库
               val renameTableSQL= "ALTER TABLE user_info_table RENAME TO user_info"
               database.execSQL(renameTableSQL)
           }catch (e:SQLException){
               e.printStackTrace()
           }
        }

    }
    private val AUTO_MIGRATION_SPEC=object :AutoMigrationSpec{
        override fun onPostMigrate(db: SupportSQLiteDatabase) {
            super.onPostMigrate(db)
            try {
                //SQL语句来升级数据库
                val renameTableSQL= "ALTER TABLE user_info_table RENAME TO user_info"
                db.execSQL(renameTableSQL)
            }catch (e:SQLException){
                e.printStackTrace()
            }
        }
    }
    /**
     * 初始化
     */
    fun initRoom(ctx:Context){
       roomDb= Room.databaseBuilder(ctx,AppDataBase::class.java, parkDataBaseName)
           //.addMigrations(MIGRATION_2_3)
           //.addAutoMigrationSpec(AUTO_MIGRATION_SPEC)
           .build()
    }
}